<template>
  <div class="filter-form">
    <div class="panel">
      <div class="panel-heading">
        Filter
        <button
          type="button"
          class="btn btn-success btn-rounded btn-xs"
          @click="addFilter"
        >Add Filter</button>
        <button
          type="button"
          class="btn btn-danger btn-rounded btn-xs"
          @click="clearFilter"
        >Clear All</button>
      </div>
      <div>
        <div @keydown.enter="performFilter" style="padding-left: 30px;">
          <div>
            <div class="row">
              <div class="col-md-6">
                <div
                  class="row"
                  :key="'filter' + index"
                  v-for="(filter, index) in opt.filters"
                  style="margin-top: 2px; margin-bottom: 2px;"
                >
                  <div class="col-md-4">
                    <select class="form-control" v-model="filter.column">
                      <option
                        :key="'column' + index"
                        v-for="(column, index) in columns"
                        :value="column"
                      >{{column.label}}</option>
                    </select>
                    <!--<v-select v-model="filter.column" :options="columns" :searchable="false"-->
                    <!--:multiple="false" :on-change="onSelectFilterChange(filter)"></v-select>-->
                  </div>
                  <div class="col-md-6">
                    <input
                      v-if="!filter.column || filter.column.inputType === 'text'"
                      class="form-control"
                      type="text"
                      v-model="filter.value"
                    >
                    <input
                      v-else-if="filter.column.inputType === 'date'"
                      v-model="filter.value"
                      class="form-control"
                      type="date"
                    >
                    <date-button
                      v-else-if="filter.column.inputType === 'dateRange' || filter.column.inputType === 'dateTimeRange' || filter.column.inputType === 'dateTimeRangeUTC'"
                      :range="true"
                      :defaultToNow="true"
                      v-model="filter.value"
                    ></date-button>
                    <select
                      v-else-if="filter.column.inputType === 'select'"
                      class="form-control"
                      v-model="filter.value"
                    >
                      <option
                        :key="'option' + index"
                        v-for="(option, index) in filter.column.options"
                        :value="option.value"
                      >{{option.label}}</option>
                    </select>
                    <range
                      v-else-if="filter.column.inputType === 'numberRange'"
                      v-model="filter.value"
                      type="number"
                    ></range>

                    <div v-else-if="filter.column.inputType === 'options'" class="row">
                      <div class="col-md-6">
                        <select class="form-control" v-model="cleanWeekday">
                          <option value="Monday">Monday</option>
                          <option value="Tuesday">Tuesday</option>
                          <option value="Wednesday">Wednesday</option>
                          <option value="Thursday">Thursday</option>
                          <option value="Friday">Friday</option>
                          <option value="Saturday">Saturday</option>
                          <option value="Sunday">Sunday</option>
                        </select>
                      </div>
                      <div class="col-md-6">
                        <select class="form-control" v-model="cleanTimeRange">
                          <option value="morning">Morning</option>
                          <option value="evening">Evening</option>
                          <option value="all_day">All Day</option>
                        </select>
                      </div>
                    </div>

                    <MySelect
                      v-else-if="filter.column.inputType === 'myselect'"
                      :id="filter.column.key"
                      v-model="filter.value"
                      :options="filter.column.options"
                      :searchable="filter.searchable"
                      :ajax="filter.column.ajax"
                    ></MySelect>
                  </div>
                  <div class="col-md-2">
                    <button
                      type="button"
                      class="btn btn-default btn-flat form-control"
                      @click="removeFilter(filter)"
                    >remove</button>
                  </div>
                </div>
              </div>
              <div class="col-md-5">
                <slot name="other_filter"></slot>
              </div>
            </div>
            <div class="row" style="padding-bottom: 20px; padding-top: 5px;">
              <div class="col-md-2">
                <div class="clearfix">
                  <button
                    type="button"
                    class="btn btn-success btn-rounded pull-left btn-sm"
                    @click="performFilter"
                  >Apply Filter</button>
                  <div class="filter-slot"><slot name="filter-form-slot"></slot></div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// components
import DateButton from "@/components/widgets/Datepicker/DateButton";
import MySelect from "@/components/widgets/MySelect";
import Range from "@/components/widgets/Range";
//import moment from 'moment'
// import vSelect from 'vue-select'
export default {
  name: "FilterForm",
  components: { DateButton, Range, MySelect },
  mounted() {
    this.addFilter();
  },
  props: {
    columns: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      opt: {
        filters: []
      },
      cleanWeekday: "Monday",
      cleanTimeRange: "morning"
    };
  },
  methods: {
    unwrap(value) {
      if (typeof value === "object") {
        return value.value;
      } else {
        return value;
      }
    },
    performFilter() {
      let opt = JSON.parse(JSON.stringify(this.opt));
      let tmp = [];
      let hasRemoveDuplicate = false;
      for (let i in opt.filters) {
        if (opt.filters[i].column.isRemoveDuplicate) {
          hasRemoveDuplicate = true;
        }

        if (
          opt.filters[i].column.inputType === "dateTimeRange" &&
          opt.filters[i].value.indexOf("/") !== -1
        ) {
          let range = opt.filters[i].value.split("/");
          let key = this.unwrap(opt.filters[i].column);
          tmp.push({
            column: key + "__gte",
            value: moment(range[0] + " 00:00:00").format("YYYY-MM-DD HH:mm:ss")
          });
          tmp.push({
            column: key + "__lte",
            value: moment(range[1] + " 23:59:59").format("YYYY-MM-DD HH:mm:ss")
          });
        } else if (
          opt.filters[i].column.inputType === "dateTimeRangeUTC" &&
          opt.filters[i].value.indexOf("/") !== -1
        ) {
          let range = opt.filters[i].value.split("/");
          let key = this.unwrap(opt.filters[i].column);
          tmp.push({
            column: key + "__gte",
            value: moment(range[0] + " 00:00:00")
              .subtract(8, "hours")
              .format("YYYY-MM-DD HH:mm:ss")
          });
          tmp.push({
            column: key + "__lte",
            value: moment(range[1] + " 23:59:59")
              .subtract(8, "hours")
              .format("YYYY-MM-DD HH:mm:ss")
          });
        } else if (
          opt.filters[i].column.inputType === "dateRange" &&
          opt.filters[i].value.indexOf("/") !== -1
        ) {
          let range = opt.filters[i].value.split("/");
          let key = this.unwrap(opt.filters[i].column);
          tmp.push({
            column: key + "__gte",
            value: range[0]
          });
          tmp.push({
            column: key + "__lt",
            value: moment(range[1])
              .add(1, "days")
              .format("YYYY-MM-DD")
          });
        } else if (opt.filters[i].column.inputType === "options") {
          tmp.push({
            column: "available_time__weekday",
            value: this.cleanWeekday
          });

          if (this.cleanTimeRange !== "all_day") {
            tmp.push({
              column:
                this.cleanTimeRange === "morning"
                  ? "available_time__start_time__lt"
                  : "available_time__end_time__gte",
              value: "12:00:00"
            });
          } else {
            tmp.push({
              column: "available_time__start_time__lte",
              value: "09:00:00"
            });
            tmp.push({
              column: "available_time__end_time__gte",
              value: "18:00:00"
            });
          }
        } else {
          tmp.push({
            rawFilter: opt.filters[i].column.rawFilter,
            column: this.unwrap(opt.filters[i].column),
            value:
              typeof opt.filters[i].value === "string"
                ? opt.filters[i].value.trim()
                : opt.filters[i].value
          });
        }
      }
      opt.filters = tmp;
      this.$emit("submit", opt, hasRemoveDuplicate);
    },
    addFilter() {
      this.opt.filters.push({ column: this.columns[0], value: "" });
    },
    clearFilter() {
      this.opt.filters = [];
      this.$emit("input", this.opt.filters);
    },
    removeFilter(filter) {
      this.opt.filters.splice(this.opt.filters.indexOf(filter), 1);
    }
  }
};
</script>

<style lang="stylus">
.filter-form {
  .select2-container .select2-selection--single {
    height: 38px !important;
  }

  .select2-container--default .select2-selection--single .select2-selection__rendered {
    line-height: 38px !important;
  }

  .select2-container--default .select2-selection--single .select2-selection__arrow {
    height: 38px !important;
  }

  .filter-slot{
    line-height 40px;
    width :500px;
    /*background-color #00AEEF;*/
    margin-left :90px;
  }
}
</style>
